import enumCmds from "../em/enumCmds"
import enumMode from "../em/enumMode"
import enumMesg from "../em/enumMesg"
import supScoket from "../sup/supScoket"
import supModule from "../sup/supModule"
import supScripts from "../sup/supScripts";
import infosModule from "./infosModule"
import aconsole from "../api/ts/api_console"
import wbsocket from "../api/ts/api_websocket"

export default class wnetsModule extends supScoket {
    private ws: wbsocket = new wbsocket(this);
    constructor() {
        super(enumMode.mesgeModule);
        this.host = "ws://127.0.0.1:23001";
        this.ws.connect()
    }

    public onopen(): void {
        this.heartbeat()
        let login: s2c_loginResult = infosModule.getData(enumMesg.s2c_loginResult)
        if (login) {
            let mod: supModule = supModule.getModule(enumMode.loginModule)
            mod.changeStart()

        } else {
            let mod: supModule = supModule.getModule(enumMode.loginModule)
            mod.changeStart()
        }
    }

    public heartbeat(): void {
        if (this.ws.readyState()) {
            setTimeout(() => {
                this.sendcmds(["heartbeat"])
                this.heartbeat()
            }, 60 * 900)
        }
    }

    public onclose(): void {
        setTimeout(() => {

            this.ws.connect()
        }, 500)
    }

    public onmessage(data: msgBody): void {
        let cmd = data.cmds.pop();
        let mod: typeof supScripts = null;
        switch (cmd) {
            case enumCmds.login: { mod = this.getModule(enumMode.loginModule) } break//登陆
            case enumCmds.lobby: { mod = this.getModule(enumMode.lobbyModule) } break//大厅
            case enumCmds.games: { mod = this.getModule(enumMode.gamesModule) } break//游戏
        }

        if (mod instanceof supScripts) {
            mod.dispatchs(data);
        }
        else {
            aconsole.msgLog(cmd + ":No recipient was found")
        }
    }

    public sendmail(name: string, cmds: string[], data: any) {
        this.ws.sendmail(name, cmds, data);
    }

    public sendcmds(cmds: string[]) {
        this.sendmail("msgBody", cmds, {});
    }

}